package com.mitac.mcd.cs.mobiletracking.messageserver;

import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.mitac.mcd.cs.mobiletracking.messageserver.util.BusinessUtil;
import com.mitac.mcd.cs.mobiletracking.messageserver.util.ClientCMDEnum;
import com.mitac.mcd.cs.mobiletracking.messageserver.util.DBConnection;
import com.mitac.mcd.cs.mobiletracking.messageserver.util.DeviceBean;
import com.mitac.mcd.cs.mobiletracking.messageserver.util.Formatter;
import com.mitac.mcd.cs.mobiletracking.messageserver.util.MsgBean;
import com.mitac.mcd.cs.mobiletracking.messageserver.util.RandomId;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



public class MobileServerThread extends Thread{

	MobileServer server;
    Socket socket;
    java.sql.Connection db = null;
    public String exceptionPropCode = null;
    int status = 1;//1 means success, 0 means error
    int type=-1;
    public PrintStream PS = null;
    public String clientAddress = null;
    private Calendar recStartTime = null;
    private Calendar recFinishTime = null;
    boolean isValidate = true;
    
    public MobileServerThread(MobileServer server,Socket socket) {
        this.server = server;
        this.socket = socket;
        try {
			PS = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		clientAddress = socket.getInetAddress().getHostAddress();
		/**********************begin check ip address************************/
        if (MobileServer.notificationIpaddressBlock){//需要check ip地址来源
        	if (!BusinessUtil.checkAcceptableIpAddress(clientAddress)){
        		isValidate = false;
        	}
        }
        /**********************end check ip address************************/
        this.start();
    }
	
    /**
     * get appropriate socket server ip and port
     * @return
     */
    public Map<String,String> getSocketServer(){
    	Map<String,String> map = new HashMap<String,String>();
    	String ip = null;String port = null;
    	//how to get most appropriate socket server---TBD
    	map.put("ip", ip);
    	map.put("port", port);
    	return map;
    }
    
    public void run() {
    	if(!isValidate){
    		BusinessUtil.aLogger.info(clientAddress+"是不被允许notification的地址，中断本次访问...");
    		if (!socket.isClosed()){
    			try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
    		}
    		return;
    	}
    	String time = Formatter.r_sdf.format(new Date());
    	String ID = time+"_"+RandomId.getRandomString(6);
    	BusinessUtil.aLogger.info("新开一个线程:"+socket+" ID:"+ID);
        BufferedReader inBr = null;
        String str = null;
        InputStream Is = null;
        try {
        	boolean flowFlag = true;
        	Is = socket.getInputStream();
            inBr = new BufferedReader(new InputStreamReader(Is,MobileServer.ENCODING));
            str = inBr.readLine();
            BusinessUtil.aLogger.info("接收到的讯息为:"+str);
            JSONObject jsonObject = null;
            List<Map> noteList = new ArrayList<Map>();
            if(str!=null&&!"".equals(str)){
            	try{
            		jsonObject = JSONObject.fromObject(str);
            	}catch(Exception e1){//上传数据格式不是规范的json格式
            		e1.printStackTrace();
            		exceptionPropCode = "E008";
            		status = 0;
        			BusinessUtil.sendMessage("aut",status,exceptionPropCode,PS);
        			flowFlag = false;
            	}
            	if(flowFlag){//validate successfully then continue
            		//request为验证
                    if (BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.notificationcmd)){
                    	BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.notificationcmd);
                    	//set rec start time
                    	recStartTime = Calendar.getInstance();
                    	
                    	JSONArray array = null;
                        boolean newest=false;
                        try{
                        	//type 0 表示 message, 1 表示 order
                            type = Integer.parseInt(jsonObject.get("type").toString());
                            //True 代表此條訊息通知是新的提交. 若是false 則代表是client 閱讀了unread 資訊, Socket Server 遞送新的 badge 資訊給 client.
                            newest = jsonObject.getBoolean("newest");
                            array = JSONArray.fromObject(jsonObject.get("clients").toString());
                            Object [] objectArray = array.toArray();
                            for(Object obj:objectArray){
                            	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
                            	String uuid = jsonObjectItem.getString("uid");
                            	int badge = jsonObjectItem.getInt("badge");
                            	Map map = new HashMap();
                            	map.put("uid", uuid);
                            	map.put("badge", badge);
                            	noteList.add(map);
                            }
                        }catch(Exception e){
                        	e.printStackTrace();
                        	String note = clientAddress+"发送的讯息不是规范的json格式，系统无法正常解析，中断本线程...";
                        	exceptionPropCode = "E008";
                    		status = 0;
                        	BusinessUtil.aLogger.info(note);
                        	BusinessUtil.sendMessage("renotificationcmd",status,exceptionPropCode,PS);
                        	flowFlag = false;
                        }
                        if(flowFlag){
                        	//return message to client
                            BusinessUtil.sendMessage("renotificationcmd",status,exceptionPropCode,PS);
                            if(noteList.size()>0){
                            	sendMessage(noteList,type,newest);
                            }
                        }
                        //set rec finish time
                        recFinishTime = Calendar.getInstance();
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.groupupdatecmd)){
                    	BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.groupupdatecmd);
                    	JSONArray uuid_array = null;JSONArray userid_array = null;
                    	List<String> uuid_list = new ArrayList<String>();List<String> userid_list = new ArrayList<String>();
                    	try{
	                    	if(jsonObject.get("uuidclients")!=null){
	                    		uuid_array = JSONArray.fromObject(jsonObject.get("uuidclients").toString());
	                    	}
	                    	if(jsonObject.get("useridclients")!=null){
	                    		userid_array = JSONArray.fromObject(jsonObject.get("useridclients").toString());
	                    	}
                    	}catch(Exception e){
                        	e.printStackTrace();
                        	String note = clientAddress+"发送的讯息不是规范的json格式，系统无法正常解析，中断本线程...";
                        	exceptionPropCode = "E008";
                    		status = 0;
                        	BusinessUtil.aLogger.info(note);
                        	BusinessUtil.sendMessage("retransgroupupdatecmd",status,exceptionPropCode,PS);
                        	flowFlag = false;
                        }
                    	if(flowFlag){
                        	//return message to client
                            BusinessUtil.sendMessage("retransgroupupdatecmd",status,exceptionPropCode,PS);
                            //查询在线的用户
                            List<MsgBean> uid_list = new ArrayList<MsgBean>();
                            List<MsgBean> sid_list = new ArrayList<MsgBean>();
                            if (uuid_array!=null){
                            	Object [] uuidArray = uuid_array.toArray();
                                for(Object obj:uuidArray){
                                	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
                                	String uuid = jsonObjectItem.getString("uid");
                                	uuid_list.add(uuid);
                                }
                                List<Map> online_uuid_List = getOnlineInfoForUUID(uuid_list);
                                for(Map map:online_uuid_List){
                                	String t_uuid = (String) map.get("uuid");
                                	int serverId = Integer.parseInt(map.get("serverId").toString());
                                	String[] server = MobileServer.servers.get(String.valueOf(serverId)).split(":");
                                	boolean flag = true;
                                	for(MsgBean bean:uid_list){
                                		if(bean.serverId==serverId){
                                			DeviceBean dbean = new DeviceBean();
                                			dbean.uuid = t_uuid;
                                			bean.list.add(dbean);
                                			flag = false;
                                		}
                                	}
                                	if (flag){
                                		DeviceBean dbean = new DeviceBean();
                            			dbean.uuid = t_uuid;
                            			MsgBean bean = new MsgBean();
                            			bean.ip = server[0];
                            			bean.port = Integer.parseInt(server[1]);
                            			bean.serverId = serverId;
                            			bean.list.add(dbean);
                            			uid_list.add(bean);
                                	}
                                }
                                for(MsgBean bean:uid_list){
                                	if (bean.list.size()>0){
                                		sendUpdMsgToSocketServerForUUID(bean);
                                	}
                                }
                            }
                            if (userid_array!=null){
                            	Object [] useridArray = userid_array.toArray();
                                for(Object obj:useridArray){
                                	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
                                	String userid = jsonObjectItem.getString("userid");
                                	userid_list.add(userid);
                                }
                                List<Map> online_userid_List = getOnlineInfoForUserID(userid_list);
                                for(Map map:online_userid_List){
                                	String t_uuid = (String) map.get("uuid");
                                	int userId = Integer.parseInt(map.get("user_id").toString());
                                	int serverId = Integer.parseInt(map.get("serverId").toString());
                                	String[] server = MobileServer.servers.get(String.valueOf(serverId)).split(":");
                                	boolean flag = true;
                                	for(MsgBean bean:sid_list){
                                		if(bean.serverId==serverId){
                                			DeviceBean dbean = new DeviceBean();
                                			dbean.uuid = t_uuid;
                                			dbean.userId = userId;
                                			bean.list.add(dbean);
                                			flag = false;
                                		}
                                	}
                                	if (flag){
                                		DeviceBean dbean = new DeviceBean();
                            			dbean.uuid = t_uuid;
                            			dbean.userId = userId;
                            			MsgBean bean = new MsgBean();
                            			bean.ip = server[0];
                            			bean.port = Integer.parseInt(server[1]);
                            			bean.serverId = serverId;
                            			bean.list.add(dbean);
                            			sid_list.add(bean);
                                	}
                                }
                                for(MsgBean bean:sid_list){
                                	if (bean.list.size()>0){
                                		sendUpdMsgToSocketServerForUSERID(bean);
                                	}
                                }
                            }
                            
                        }
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.killcmd)){
                    	BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.killcmd);
                    	JSONArray uuid_array = null;JSONArray userid_array = null;
                    	List<String> uuid_list = new ArrayList<String>();List<String> userid_list = new ArrayList<String>();
                    	try{
	                    	if(jsonObject.get("uuidclients")!=null){
	                    		uuid_array = JSONArray.fromObject(jsonObject.get("uuidclients").toString());
	                    	}
	                    	if(jsonObject.get("useridclients")!=null){
	                    		userid_array = JSONArray.fromObject(jsonObject.get("useridclients").toString());
	                    	}
                    	}catch(Exception e){
                        	e.printStackTrace();
                        	String note = clientAddress+"发送的讯息不是规范的json格式，系统无法正常解析，中断本线程...";
                        	exceptionPropCode = "E008";
                    		status = 0;
                        	BusinessUtil.aLogger.info(note);
                        	BusinessUtil.sendMessage("retransgroupupdatecmd",status,exceptionPropCode,PS);
                        	flowFlag = false;
                        }
                    	if(flowFlag){
                            //查询在线的用户
                            List<MsgBean> uid_list = new ArrayList<MsgBean>();
                            List<MsgBean> sid_list = new ArrayList<MsgBean>();
                            if (uuid_array!=null){
                            	Object [] uuidArray = uuid_array.toArray();
                                for(Object obj:uuidArray){
                                	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
                                	String uuid = jsonObjectItem.getString("uid");
                                	uuid_list.add(uuid);
                                }
                                List<Map> online_uuid_List = getOnlineInfoForUUID(uuid_list);
                                for(Map map:online_uuid_List){
                                	String t_uuid = (String) map.get("uuid");
                                	int serverId = Integer.parseInt(map.get("serverId").toString());
                                	String[] server = MobileServer.servers.get(String.valueOf(serverId)).split(":");
                                	boolean flag = true;
                                	for(MsgBean bean:uid_list){
                                		if(bean.serverId==serverId){
                                			DeviceBean dbean = new DeviceBean();
                                			dbean.uuid = t_uuid;
                                			bean.list.add(dbean);
                                			flag = false;
                                		}
                                	}
                                	if (flag){
                                		DeviceBean dbean = new DeviceBean();
                            			dbean.uuid = t_uuid;
                            			MsgBean bean = new MsgBean();
                            			bean.ip = server[0];
                            			bean.port = Integer.parseInt(server[1]);
                            			bean.serverId = serverId;
                            			bean.list.add(dbean);
                            			uid_list.add(bean);
                                	}
                                }
                                for(MsgBean bean:uid_list){
                                	if (bean.list.size()>0){
                                		sendKillMsgToSocketServerForUUID(bean);
                                	}
                                }
                            }
                            if (userid_array!=null){
                            	Object [] useridArray = userid_array.toArray();
                                for(Object obj:useridArray){
                                	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
                                	String userid = jsonObjectItem.getString("userid");
                                	userid_list.add(userid);
                                }
                                List<Map> online_userid_List = getOnlineInfoForUserID(userid_list);
                                for(Map map:online_userid_List){
                                	String t_uuid = (String) map.get("uuid");
                                	int userId = Integer.parseInt(map.get("user_id").toString());
                                	int serverId = Integer.parseInt(map.get("serverId").toString());
                                	String[] server = MobileServer.servers.get(String.valueOf(serverId)).split(":");
                                	boolean flag = true;
                                	for(MsgBean bean:sid_list){
                                		if(bean.serverId==serverId){
                                			DeviceBean dbean = new DeviceBean();
                                			dbean.uuid = t_uuid;
                                			dbean.userId = userId;
                                			bean.list.add(dbean);
                                			flag = false;
                                		}
                                	}
                                	if (flag){
                                		DeviceBean dbean = new DeviceBean();
                            			dbean.uuid = t_uuid;
                            			dbean.userId = userId;
                            			MsgBean bean = new MsgBean();
                            			bean.ip = server[0];
                            			bean.port = Integer.parseInt(server[1]);
                            			bean.serverId = serverId;
                            			bean.list.add(dbean);
                            			sid_list.add(bean);
                                	}
                                }
                                for(MsgBean bean:sid_list){
                                	if (bean.list.size()>0){
                                		sendKillMsgToSocketServerForUSERID(bean);
                                	}
                                }
                            }
                            
                        }
                    	//return message to client
                        BusinessUtil.sendMessage("rekillcmd",status,exceptionPropCode,PS);
                    	
                    }
            	}
            }
	        
        }catch (SocketException ex) {
            BusinessUtil.aLogger.info(" ERROR:"+ex);
        }catch(IOException e){
            BusinessUtil.aLogger.info(" ERROR:"+e);
        }finally{
            try {
                if (!socket.isClosed()) socket.close();
                Is.close();
                inBr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            BusinessUtil.aLogger.info(ID+" 线程已经结束.....");
        }
    }
    
    public void sendKillMsgToSocketServerForUUID(MsgBean bean) {
    	Socket socket = null;
    	OutputStream Os = null;
		PrintStream PS = null;
		
    	socket = new Socket();
    	SocketAddress socketaddress = new InetSocketAddress(bean.ip,bean.port);
		try {
			socket.connect(socketaddress,5*1000);
			if (!socket.isClosed()){
	            Os = socket.getOutputStream();
	            PS = new PrintStream(Os);
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"cmd\":\"transkillcmd\"");
			sb.append(",");
			sb.append("\"uuidclients\":");
			sb.append("[");
			for(DeviceBean dbean:bean.list){
				sb.append("{\"uid\":").append("\"").append(dbean.uuid).append("\"");
				sb.append("}");
				sb.append(",");
			}
			String jsonStr = sb.substring(0, sb.length()-1);
			jsonStr = jsonStr +"]}";
			
			PS.println(jsonStr);
			PS.close();
	        Os.close();
	        socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			BusinessUtil.aLogger.info("sendKillMsgToSocketServerForUUID失败...."+"ID:"+bean.ID+";ip:"+bean.ip+";port:"+bean.ip);
		}
		
	}
    
    public void sendKillMsgToSocketServerForUSERID(MsgBean bean){
    	Socket socket = null;
    	OutputStream Os = null;
		PrintStream PS = null;
		
    	socket = new Socket();
    	SocketAddress socketaddress = new InetSocketAddress(bean.ip,bean.port);
		try {
			socket.connect(socketaddress,5*1000);
			if (!socket.isClosed()){
	            Os = socket.getOutputStream();
	            PS = new PrintStream(Os);
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"cmd\":\"transkillcmd\"");
			sb.append(",");
			sb.append("\"useridclients\":");
			sb.append("[");
			for(DeviceBean dbean:bean.list){
				sb.append("{\"userid\":").append(dbean.userId);
				sb.append("}");
				sb.append(",");
			}
			String jsonStr = sb.substring(0, sb.length()-1);
			jsonStr = jsonStr +"]}";
			
			PS.println(jsonStr);
			PS.close();
	        Os.close();
	        socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			BusinessUtil.aLogger.info("sendKillMsgToSocketServerForUSERID失败...."+"ID:"+bean.ID+";ip:"+bean.ip+";port:"+bean.ip);
		}
		
	}
    
    public void sendUpdMsgToSocketServerForUUID(MsgBean bean) {
    	Socket socket = null;
    	OutputStream Os = null;
		PrintStream PS = null;
		
    	socket = new Socket();
    	SocketAddress socketaddress = new InetSocketAddress(bean.ip,bean.port);
		try {
			socket.connect(socketaddress,5*1000);
			if (!socket.isClosed()){
	            Os = socket.getOutputStream();
	            PS = new PrintStream(Os);
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"cmd\":\"transgroupupdatecmd\"");
			sb.append(",");
			sb.append("\"uuidclients\":");
			sb.append("[");
			for(DeviceBean dbean:bean.list){
				sb.append("{\"uid\":").append("\"").append(dbean.uuid).append("\"");
				sb.append("}");
				sb.append(",");
			}
			String jsonStr = sb.substring(0, sb.length()-1);
			jsonStr = jsonStr +"]}";
			
			PS.println(jsonStr);
			PS.close();
	        Os.close();
	        socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			BusinessUtil.aLogger.info("sendUpdMsgToSocketServerForUUID失败...."+"ID:"+bean.ID+";ip:"+bean.ip+";port:"+bean.ip);
		}
		
	}
    
    public void sendUpdMsgToSocketServerForUSERID(MsgBean bean) {
    	Socket socket = null;
    	OutputStream Os = null;
		PrintStream PS = null;
		
    	socket = new Socket();
    	SocketAddress socketaddress = new InetSocketAddress(bean.ip,bean.port);
		try {
			socket.connect(socketaddress,5*1000);
			if (!socket.isClosed()){
	            Os = socket.getOutputStream();
	            PS = new PrintStream(Os);
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"cmd\":\"transgroupupdatecmd\"");
			sb.append(",");
			sb.append("\"useridclients\":");
			sb.append("[");
			for(DeviceBean dbean:bean.list){
				sb.append("{\"userid\":").append(dbean.userId);
				sb.append("}");
				sb.append(",");
			}
			String jsonStr = sb.substring(0, sb.length()-1);
			jsonStr = jsonStr +"]}";
			
			PS.println(jsonStr);
			PS.close();
	        Os.close();
	        socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			BusinessUtil.aLogger.info("sendUpdMsgToSocketServerForUSERID失败...."+"ID:"+bean.ID+";ip:"+bean.ip+";port:"+bean.ip);
		}
		
	}

	public void sendMessage(List<Map> noteList,int type,boolean newest){
    	Hashtable<String, String> notes = new Hashtable<String, String>();
    	List<MsgBean> list = new ArrayList<MsgBean>();
    	List<String> uuidlist = new ArrayList<String>();
    	String time = Formatter.r_sdf.format(new Date());
    	String ID = time+"_"+RandomId.getRandomString(6);
    	for(Map map:noteList){
    		uuidlist.add(map.get("uid").toString());
    		notes.put(map.get("uid").toString(), map.get("badge").toString());
    		BusinessUtil.logNotificationDetail(ID, map.get("uid").toString(), map.get("badge").toString());
    	}
    	BusinessUtil.logNotification(ID, type, noteList.size(), null, newest);
    	
    	List<Map> resultList = getOnlineInfoForUUID(uuidlist);
        for(Map map:resultList){
        	String t_uuid = (String) map.get("uuid");
        	int serverId = Integer.parseInt(map.get("serverId").toString());
        	String[] server = MobileServer.servers.get(String.valueOf(serverId)).split(":");
        	boolean flag = true;
        	for(MsgBean bean:list){
        		if(bean.serverId==serverId){
        			DeviceBean dbean = new DeviceBean();
        			dbean.uuid = t_uuid;
        			dbean.badge = Integer.parseInt(notes.get(t_uuid).toString());
        			bean.list.add(dbean);
        			flag = false;
        		}
        	}
        	if (flag){
        		DeviceBean dbean = new DeviceBean();
    			dbean.uuid = t_uuid;
    			dbean.badge = Integer.parseInt(notes.get(t_uuid).toString());
    			MsgBean bean = new MsgBean();
    			bean.ip = server[0];
    			bean.port = Integer.parseInt(server[1]);
    			bean.serverId = serverId;
    			bean.ID = ID;
    			bean.type = type;
    			bean.newest = newest;
    			bean.list.add(dbean);
    			list.add(bean);
        	}
        }
        for(MsgBean bean:list){
        	if (bean.list.size()>0){
        		sendMsgToSocketServer(bean);
        	}
        }
    }
    
    public void sendMsgToSocketServer(MsgBean bean){
    	Socket socket = null;
    	OutputStream Os = null;
		PrintStream PS = null;
		
    	socket = new Socket();
    	SocketAddress socketaddress = new InetSocketAddress(bean.ip,bean.port);
		try {
			socket.connect(socketaddress,5*1000);
			if (!socket.isClosed()){
	            Os = socket.getOutputStream();
	            PS = new PrintStream(Os);
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"cmd\":\"transnotificationcmd\"");
			sb.append(",");
			sb.append("\"ID\":\"").append(bean.ID).append("\"");
			sb.append(",");
			sb.append("\"type\":").append(bean.type);
			sb.append(",");
			sb.append("\"newest\":").append(bean.newest);
			sb.append(",");
			sb.append("\"clients\":");
			sb.append("[");
			for(DeviceBean dbean:bean.list){
				sb.append("{\"uid\":").append("\"").append(dbean.uuid).append("\"").append(",");
				sb.append("\"badge\":").append(dbean.badge).append("}");
				sb.append(",");
			}
			String jsonStr = sb.substring(0, sb.length()-1);
			jsonStr = jsonStr +"]}";
			
			PS.println(jsonStr);
			PS.close();
	        Os.close();
	        socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			BusinessUtil.aLogger.info("sendMsgToSocketServer失败...."+"ID:"+bean.ID+";ip:"+bean.ip+";port:"+bean.port);
		}
		
    }
    
    public List<Map> getOnlineInfoForUUID(List<String> uuid_list){
    	List<Map> list = new ArrayList<Map>();
    	StringBuffer sb = new StringBuffer();
    	for(String uuid:uuid_list){
    		sb.append("'"+uuid+"',");
    	}
    	String uuidStr = sb.substring(0,sb.length()-1).toString();
    	String sql = " SELECT UUID,USER_ID,SERVER_ID FROM ONLINE_CLIENT WHERE UUID in ("+uuidStr+")";
        BusinessUtil.aLogger.info("sql==="+sql);
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
	        db = DBConnection.getConnection("gpsdata");
	        ps = db.prepareStatement(sql);
	        rs = ps.executeQuery();
	        while(rs.next()){
	        	String t_uuid = rs.getString("UUID");
	        	int serverId = rs.getInt("SERVER_ID");
	        	int user_id = rs.getInt("USER_ID");
	        	Map map = new HashMap();
	        	map.put("serverId", serverId);
	        	map.put("user_id", user_id);
	        	map.put("uuid", t_uuid);
	        	list.add(map);
	        }
	        if(null!=rs) rs.close();
	        ps.close();
	        db.close();
        }catch (SQLException e) {
        	e.printStackTrace();
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		
		return list;
    }
    
    public List<Map> getOnlineInfoForUserID(List<String> userid_list){
    	List<Map> list = new ArrayList<Map>();
    	StringBuffer sb = new StringBuffer();
    	for(String userid:userid_list){
    		sb.append(userid+",");
    	}
    	String useridStr = sb.substring(0,sb.length()-1).toString();
    	String sql = " SELECT UUID,USER_ID,SERVER_ID FROM ONLINE_CLIENT WHERE USER_ID in ("+useridStr+")";
        BusinessUtil.aLogger.info("sql==="+sql);
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
	        db = DBConnection.getConnection("gpsdata");
	        ps = db.prepareStatement(sql);
	        rs = ps.executeQuery();
	        while(rs.next()){
	        	String t_uuid = rs.getString("UUID");
	        	int serverId = rs.getInt("SERVER_ID");
	        	int user_id = rs.getInt("USER_ID");
	        	Map map = new HashMap();
	        	map.put("serverId", serverId);
	        	map.put("user_id", user_id);
	        	map.put("uuid", t_uuid);
	        	list.add(map);
	        }
	        if(null!=rs) rs.close();
	        ps.close();
	        db.close();
        }catch (SQLException e) {
        	e.printStackTrace();
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		return list;
    }
    
    public static void main(String args[]){
    	String ss = "{\"cmd\":\"groupupdatecmd\", \"uuidclients\": [{\"uid\":\"aa\"}, {\"uid\":\"bb\"}], \"useridclients\":[{\"userid\":1}, {\"userid\":1}]}";
    	JSONObject jsonObject = null;
    	jsonObject = JSONObject.fromObject(ss);
    	JSONArray array = null;
    	array = JSONArray.fromObject(jsonObject.get("uuidclients").toString());
    	Object [] objectArray = array.toArray();
        for(Object obj:objectArray){
        	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
        	String uuid = jsonObjectItem.getString("uid");
        	System.out.println(uuid);
        }
    }
}
